/*
 * This file is Copyright 2002-2006 Loyola University Chicago,
 * Department of Computer Science and the Emerging Technologies Laboratory.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License via
 *    http://www.apache.org/licenses/LICENSE-2.0.
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.citep.web.admin.accounts.client;

import com.citep.web.gwt.module.Presentation;
import com.citep.web.gwt.widgets.ShortcutTable;
import com.citep.web.gwt.widgets.StatusLabel;
import com.google.gwt.user.client.History;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.ClickListener;
import com.google.gwt.user.client.ui.HasHorizontalAlignment;
import com.google.gwt.user.client.ui.Hyperlink;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.VerticalPanel;
import com.google.gwt.user.client.ui.Widget;
import com.google.gwt.user.client.ui.Tree;
import com.google.gwt.user.client.ui.TreeItem;
import com.google.gwt.user.client.ui.TreeListener;

import com.google.gwt.user.client.Window;
import com.citep.web.gwt.widgets.DynaTable;
import com.citep.web.gwt.widgets.Shortcut;
import com.citep.web.gwt.widgets.ShortcutTable;
import com.citep.web.gwt.widgets.DataClickListener;
import com.citep.web.gwt.dto.*;
import com.citep.web.gwt.module.*;

public class AccountListPresentation extends BasePresentation implements Presentation {
	
	public void displayError(String key, String value) {
		// TODO Auto-generated method stub
		
	}

	public void displayStatus(String msg, int seconds) {
		getStatusLabel().setText(msg);
		getStatusLabel().show(seconds);
	}

	public void setLoadingState() {
		getStatusLabel().setText("Refreshing tree...");
		getStatusLabel().setVisible(true);
	}
	
	public void setReadyState() {
		getStatusLabel().hide();
	}	
	
	protected AccountListApplication application;
	
	protected Label titleLabel;
	protected StatusLabel statusLabel;
	protected VerticalPanel mainPanel;
	protected ShortcutTable shortcuts;
	
//	protected DynaTableWidget dataGrid;
	protected Tree accountTree;
	
	protected Button createAccountCategoryButton;
	protected Button createAccountButton;	

	public AccountListPresentation() {
		
	}
	
	public Tree getAccountTree() {
		if(accountTree == null) {
			accountTree = new Tree();
			accountTree.addTreeListener(new TreeListener() {
				public void onTreeItemSelected(TreeItem item) {
					AccountDTO selectedAccount = (AccountDTO)item.getUserObject();
					application.onAccountClicked(selectedAccount);
				}
				
				public void onTreeItemStateChanged(TreeItem item) {}
			});
		}
		return accountTree;
	}
	
	public void refreshAccountDetails(AccountTreeNode root) {
		updateNodeBalance(getAccountTree().getItem(0), root);
	}
	
	private void updateNodeBalance(TreeItem branch, AccountTreeNode data) {
		AccountDTO old = (AccountDTO)branch.getUserObject();
		AccountDTO current = data.getAccount();
		
		if(old.getId() == current.getId()) {
			branch.setUserObject(current);
			branch.setHTML("<img src=\"img/icon_account_ok.png\"/>"+
					"<span class=\"account_tree_name\">" + 
					current.getName() +
					"</span><span class=\"account_tree_type\">(" + 
					current.getType() + 
					"</span><span class=\"account_tree_balance\">balance=" + current.getCurrentBalance() + ")</span>");
			
			if(data.getChildren() != null) {
				for(int i = 0; i < branch.getChildCount(); i++)
					for(int j = 0; j < data.getChildren().size(); j++) {
						old = (AccountDTO)branch.getChild(i).getUserObject();
						current = ((AccountTreeNode)data.getChildren().get(j)).getAccount();
						
						if(old.getId() == current.getId()) {
							updateNodeBalance(branch.getChild(i), (AccountTreeNode)data.getChildren().get(j));
							break;
						}
					}
			}
			
		} else {
			System.out.println("ERROR: old: " + old + " does not match current: " + current);
		}
	}
	
	
	public void refreshAccountTree(AccountTreeNode root) {
		getAccountTree().removeItems();
		TreeItem start = new TreeItem(root.getAccount().getName());
		start.setUserObject(root.getAccount());
		populateTreeNode(root,start);
		getAccountTree().addItem(start);
	}
	
	private void populateTreeNode(AccountTreeNode data, TreeItem branch) {
		branch.setUserObject(data.getAccount());
		branch.setHTML("<img src=\"img/icon_account_ok.png\"/>"+
				"<span class=\"account_tree_name\">" + 
				data.getAccount().getName() +
				"</span><span class=\"account_tree_type\">(" + 
				data.getAccount().getType() + 
				"</span><span class=\"account_tree_balance\">balance=" + data.getAccount().getCurrentBalance() + ")</span>");
		
		if(data.hasChildren()) {
			for(int i = 0; i < data.getChildren().size(); i++) {
				AccountTreeNode child = (AccountTreeNode)data.getChildren().get(i);
				TreeItem sprout = new TreeItem();
				populateTreeNode(child,sprout);
				branch.addItem(sprout);
			}
		}
	}

	public void setApplication(AccountListApplication application) {
		this.application = application;
	}	

	public Label getTitleLabel() {
		if(titleLabel == null) {
			titleLabel = new Label("Chart of Accounts");
			titleLabel.setStyleName("form_title");
		}
		
		return titleLabel;
	}
	
	private StatusLabel getStatusLabel() {
		if(statusLabel == null) {
			statusLabel = new StatusLabel();
			statusLabel.setStyleName("status_label_small");
			statusLabel.setText("text");
			statusLabel.hide();
		}

		return statusLabel;
	}
	
	protected Button getCreateAccountButton() {
		if(createAccountButton == null) {
			createAccountButton = new Button("Create Account");
			createAccountButton.setStyleName("form_button");
			createAccountButton.addClickListener(new ClickListener() {
				public void onClick(Widget w) {
					String token = HistoryEncoder.encode("account_entry", null);
					History.newItem(token);
				}
			});
		}
		
		return createAccountButton;
	}
	
	protected Button getCreateAccountCategoryButton() {
		if(createAccountCategoryButton == null) {
			createAccountCategoryButton = new Button("Create Account Category");
			createAccountCategoryButton.setStyleName("form_button");
		}
		
		return createAccountCategoryButton;
	}	
	
	public void addShortCut(Shortcut s, boolean highlight) {
		shortcuts.addShortcut(s, highlight);
	}
	
	
	public Widget getMainPanel() {
		if(mainPanel == null) {
			mainPanel = new VerticalPanel();
			mainPanel.setWidth("100%");
			//mainPanel.add(getTitleLabel());
			getTitlePanel().setHorizontalAlignment(HasHorizontalAlignment.ALIGN_CENTER);
			getTitlePanel().add(getStatusLabel());
			mainPanel.add(getTitlePanel());
			//mainPanel.add(getDataGrid());
			//mainPanel.add(getStatusLabel());
			mainPanel.add(getAccountTree());
			
			//mainPanel.setCellHorizontalAlignment(getDataGrid(), HasHorizontalAlignment.ALIGN_CENTER);
			mainPanel.setCellHorizontalAlignment(getStatusLabel(), HasHorizontalAlignment.ALIGN_CENTER);
		}
		return mainPanel;
	}
	
	public Widget getContext() {
		
		VerticalPanel p = new VerticalPanel();
		p.setStyleName("table_center");
		p.setSpacing(0);
		
		shortcuts = new ShortcutTable("Categories",10);
		shortcuts.setMoreLink(new Hyperlink("[more]","__account_list__"));
		
		p.add(getCreateAccountButton());
		p.add(shortcuts);
		
		return p;
	}	
}
